package com.azkj.album.view.activity;

import android.Manifest;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.viewpager2.widget.ViewPager2;

import com.azkj.album.R;
import com.azkj.album.adapter.PicsAdapter;
import com.azkj.album.adapter.TabAdapter;
import com.azkj.album.dto.ListData;
import com.azkj.album.dto.MessageEvent;
import com.azkj.album.dto.MessageType;
import com.azkj.album.dto.Pics;
import com.azkj.album.network.ConfigStorage;
import com.azkj.album.network.Constants;
import com.azkj.album.network.NetworkMaster;
import com.azkj.album.network.callback.ServiceCallback;
import com.azkj.album.network.networkframe.bean.BaseResp;
import com.azkj.album.network.networkframe.net.exception.ApiException;
import com.azkj.album.network.utils.MyDateUtils;
import com.azkj.album.network.utils.ToastUtils;
import com.azkj.album.utils.DownLoadApkUtils;
import com.azkj.album.utils.PermissionsUtils;
import com.azkj.album.utils.SaveImgToLocalTool;
import com.azkj.album.view.base.BaseActivity;
import com.azkj.album.view.base.BaseFragment;
import com.azkj.album.view.fragment.detail.DetailFragment;
import com.azkj.album.view.widgets.BubbleDialog;
import com.azkj.album.view.widgets.dialog.CommonDialog;
import com.azkj.album.view.widgets.dialog.DialogHelper;
import com.azkj.album.view.widgets.dialog.ShareBottomDialog;
import com.lxj.xpopup.XPopup;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class DetailActivity extends BaseActivity {
    private static final int REQUEST_ALBUM = 101;
    public static final String FROM_TYPE_MAIN = "main";
    public static final String FROM_TYPE_COLLECT = "collect";
    public static final String FROM_TYPE_RECOVERY = "recovery";
    private String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};

    @BindView(R.id.tv_category_label)
    TextView categoryLabel;
    @BindView(R.id.tv_category_createtime)
    TextView categoryTime;

    @BindView(R.id.v_left)
    View v_left;
    @BindView(R.id.v_right)
    View v_right;

    @BindView(R.id.controller)
    LinearLayout controller;
    @BindView(R.id.del)
    TextView del;
    @BindView(R.id.collect)
    TextView collect;
    @BindView(R.id.edit)
    TextView tvEdit;

    @BindView(R.id.frame_content)
    RelativeLayout frameContent;

    @BindView(R.id.download)
    TextView downLoad;

    @BindView(R.id.ll_bottom_download_options)
    LinearLayout llDownloadOptions;

    @BindView(R.id.tv_all_select)
    TextView tvAllSelect;

    @BindView(R.id.tv_cancel)
    TextView tvCancel;

    @BindView(R.id.viewPager)
    ViewPager2 viewPager;

    @BindView(R.id.ll_title_gallery)
    LinearLayout ll_title_gallery;

    private ListData detail;
    private String fromType;

    private boolean isShowCover = true;

    private Drawable collectDrawable;
    private Drawable nunCollectDrawable;

    private TabAdapter tabAdapter;
    private DetailFragment coverFragment;
    private DetailFragment albumFragment;
    private PermissionsUtils permissionsUtils = new PermissionsUtils();

    @Override
    protected int getLayoutId() {
        return R.layout.activity_detail;
    }

    @Override
    public void initView() {
        collectDrawable = getResources().getDrawable(R.mipmap.icon3);
        collectDrawable.setBounds(0, 0, getResources().getDimensionPixelSize(R.dimen.dp_20), getResources().getDimensionPixelSize(R.dimen.dp_20));

        nunCollectDrawable = getResources().getDrawable(R.mipmap.icon_collect_black);
        nunCollectDrawable.setBounds(0, 0, getResources().getDimensionPixelSize(R.dimen.dp_20), getResources().getDimensionPixelSize(R.dimen.dp_20));

        detail = (ListData) getIntent().getSerializableExtra("detail");
        fromType = getIntent().getStringExtra("fromType");
        if (FROM_TYPE_MAIN.equals(fromType)) {
            del.setVisibility(View.VISIBLE);
        } else if (FROM_TYPE_COLLECT.equals(fromType)) {
            del.setVisibility(View.GONE);
        } else if (FROM_TYPE_RECOVERY.equals(fromType)) {
            controller.setVisibility(View.GONE);
        }

    }

    private void initFragmentAndViewPager() {
        List<BaseFragment> fragmentList = new ArrayList<>();
        coverFragment = DetailFragment.newInstance(true, detail, null);
        albumFragment = DetailFragment.newInstance(false, detail, selectAllText -> tvAllSelect.setText(selectAllText));
        fragmentList.add(coverFragment);
        fragmentList.add(albumFragment);

        tabAdapter = new TabAdapter(this, fragmentList);
        viewPager.setAdapter(tabAdapter);
        viewPager.setOffscreenPageLimit(ViewPager2.OFFSCREEN_PAGE_LIMIT_DEFAULT);
        viewPager.registerOnPageChangeCallback(changeCallback);
    }


    @Override
    public void initData() {

        initFragmentAndViewPager();

        Log.e(TAG, "detail is " + detail.toString());
        ListData.Albumcategory albumcategory = detail.getAlbumcategory();
        if (null != albumcategory) {
            categoryLabel.setText("图册分类：" + (TextUtils.isEmpty(albumcategory.getName()) ? "" : albumcategory.getName()));
            categoryTime.setText("创建时间：" + MyDateUtils.getCurrent(String.valueOf(detail.getCreatetime())));
        }

        collect.setCompoundDrawables(null, 0 == detail.isCollect() ? nunCollectDrawable : collectDrawable, null, null);
    }


    private void loadData() {
        NetworkMaster.getInstance().getCommonService().detail(detail.getId(), new ServiceCallback<BaseResp<ListData>>() {
            @Override
            public void onSuccess(BaseResp<ListData> jsonObj) {
                DialogHelper.hideDialog();
                detail = jsonObj.getData();
                initData();
            }

            @Override
            public void onError(ApiException apiException) {
                DialogHelper.hideDialog();
            }
        });

    }


    @Override
    protected void initPresenter() {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 10001) {
                detail = (ListData) data.getSerializableExtra("detail");
                if (!TextUtils.isEmpty(detail.getImages())) {
                    String[] pics = detail.getImages().split(",");
                    ArrayList<Pics> arrayList = new ArrayList<>();
                    for (String pic : pics) {
                        arrayList.add(new Pics(pic, false));
                    }
                    albumFragment.getPicsAdapter().setNewData(arrayList);
                } else {
                    detail.setImages("");
                    albumFragment.getPicsAdapter().setNewData(new ArrayList<>());
                }
                if (detail.getAlbumcategory() != null) {
                    ListData.Albumcategory albumcategory = detail.getAlbumcategory();
                    if (null != albumcategory) {
                        categoryLabel.setText("图册分类：" + (TextUtils.isEmpty(albumcategory.getName()) ? "" : albumcategory.getName()));
                        categoryTime.setText("创建时间：" + MyDateUtils.getCurrent(String.valueOf(detail.getCreatetime())));
                    }
                }
            } else if (requestCode == REQUEST_ALBUM) {     //相册返回


            }
        }
    }

    @OnClick({R.id.iv_back, R.id.v_left, R.id.v_right, R.id.share, R.id.del, R.id.download,
            R.id.collect, R.id.edit, R.id.tv_cancel, R.id.tv_all_select, R.id.tv_confirm})
    public void onViewClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.v_left:
                if (isShowCover) {
                    return;
                }
                isShowCover = true;
                changeTitle(isShowCover);
                viewPager.setCurrentItem(isShowCover ? 0 : 1);
                break;
            case R.id.v_right:
                if (!isShowCover) {
                    return;
                }
                isShowCover = false;
                changeTitle(isShowCover);
                viewPager.setCurrentItem(isShowCover ? 0 : 1);
                break;
            case R.id.share:
                showBubbleDialog();
                break;
            case R.id.del:
                new CommonDialog.Builder(this).setDesc("是否删除选中图册？").setButton("取消", "确定").setBackground(R.mipmap.ic_login_error).setOnClickListener((dialog, confirm) -> {
                    if (confirm) {
                        delGallery();
                    }
                    dialog.dismiss();
                }).show();
                break;
            case R.id.download:
                downloadImg();
                break;
            case R.id.collect:
                if (detail.isCollect() == 0) {
                    collect();
                } else {
                    cancelCollect();
                }
                break;
            case R.id.edit:
                editCoverOrAlbum();
                break;
            case R.id.tv_cancel:
                cancelSelectPic();
                break;
            case R.id.tv_all_select:
                ArrayList<String> selectedUrl = albumFragment.getSelectedUrl();
                PicsAdapter adapter = albumFragment.getPicsAdapter();
                List<Pics> data = adapter.getData();
                selectedUrl.clear();
                if (tvAllSelect.getText().toString().equals("全选")) {
                    adapter.setAllSelect(true);
                    tvAllSelect.setText("取消全选");
                    for (Pics datum : data) {
                        selectedUrl.add(datum.url);
                    }
                } else {
                    adapter.setAllSelect(false);
                    tvAllSelect.setText("全选");
                }
                break;
            case R.id.tv_confirm:
                downloadMoreUrl();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        viewPager.unregisterOnPageChangeCallback(changeCallback);
    }

    private void changeTitle(boolean isShowCover) {
        ll_title_gallery.setBackgroundResource(isShowCover ? R.mipmap.gallery_show_convers : R.mipmap.gallery_show_list);
        downLoad.setText(isShowCover ? "下载封面" : "下载图册");
        tvEdit.setText(isShowCover ? "编辑封面" : "编辑图册");

        Drawable drawableTop = ContextCompat.getDrawable(this, isShowCover ? R.mipmap.icon_edit_black : R.mipmap.icon_edit_black2);
        drawableTop.setBounds(0, 0, drawableTop.getMinimumWidth(), drawableTop.getMinimumHeight());
        tvEdit.setCompoundDrawables(null, drawableTop, null, null);

        if (isShowCover && llDownloadOptions.getVisibility() == View.VISIBLE) {
            cancelSelectPic();
        }
    }

    private void editCoverOrAlbum() {
        if (isShowCover) {
            onPhoto();

        } else {
            Intent intent = new Intent(this, NewPhotoActivity.class);
            intent.putExtra("isAddAndReducePic", true);
            intent.putExtra("detail", detail);
            startActivityForResult(intent, 10001);
        }
    }

    private void cancelSelectPic() {
        albumFragment.setDownLoadAlbum(false);
        albumFragment.getSelectedUrl().clear();
        tvAllSelect.setText("全选");
        controller.setVisibility(View.VISIBLE);
        llDownloadOptions.setVisibility(View.GONE);
        albumFragment.getPicsAdapter().setAllSelect(false);
        albumFragment.getPicsAdapter().setShowSelect(false);
    }

    private int count = 0;

    private void downloadMoreUrl() {
        ArrayList<String> selectedUrl = albumFragment.getSelectedUrl();
        if (!selectedUrl.isEmpty()) {
            showLoading("正在保存，请稍后...");
            new Thread(() -> {
                count = 0;
                for (int i = 0; i < selectedUrl.size(); i++) {
                    File file = SaveImgToLocalTool.saveImageToSdCard(getApplicationContext(), selectedUrl.get(i), String.valueOf(i));
                    if (file != null) {
                        count++;
                        try {
                            MediaStore.Images.Media.insertImage(getContentResolver(), file.getAbsolutePath(), file.getName(), null);
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                        // 最后通知图库更新
                        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse(file.getAbsolutePath())));
                    }

                }
                runOnUiThread(() -> {
                    if (selectedUrl.size() == count) {
                        hideLoading();
                        ToastUtils.showCenterToast("保存成功");
                    } else {
                        hideLoading();
                        ToastUtils.showCenterToast(selectedUrl.size() - count + "张图片保存失败");
                    }
                });
            }).start();
        } else {
            ToastUtils.showCenterToast("请选择图片");
        }
    }

    private void downloadImg() {
        if (isShowCover) {
            albumFragment.setDownLoadAlbum(false);
            downloadUrl(detail.getCoverImage(), String.valueOf(detail.getId()));
        } else {
            albumFragment.getPicsAdapter().setShowSelect(true);
            controller.setVisibility(View.GONE);
            albumFragment.setDownLoadAlbum(true);
            llDownloadOptions.setVisibility(View.VISIBLE);
        }
    }

    private void showBubbleDialog() {
        BubbleDialog bubbleDialog = new BubbleDialog(this);
        bubbleDialog.setCallBackListener(new BubbleDialog.CallBackListener() {
            @Override
            public void callBackAll() {
                showShareDialog(true);
            }

            @Override
            public void callBackSingle() {
                showShareDialog(false);
            }
        });
        new XPopup.Builder(DetailActivity.this)
                .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                .hasShadowBg(false) // 去掉半透明背景
                .atView(findViewById(R.id.share))
                .asCustom(bubbleDialog)
                .show();
    }

    private void showShareDialog(boolean isAll) {

        new ShareBottomDialog.Builder(DetailActivity.this)
                .setShowDownLoad(false).setCallBack(
                        new ShareBottomDialog.Builder.ItemClickListener() {
                            @Override
                            public void onFriendClick() {
                                copyToClipboard();
                                if (isAll) {
                                    shareWeb(detail.getChooseImage(), false, Constants.WEB_PAGE_SHARE_TASK + detail.getShareId(), detail.getIntro(), detail.getRemark());
                                } else {
                                    shareImageToWx(null, detail.getCoverImage(), true,-1);
                                }
                            }

                            @Override
                            public void onZoneClick() {
                                copyToClipboard();
                                if (isAll) {
                                    shareWeb(detail.getChooseImage(), true, Constants.WEB_PAGE_SHARE_TASK + detail.getShareId(), detail.getIntro(), detail.getRemark());
                                } else {
                                    shareImageToWx(null, detail.getCoverImage(), false,-1);
                                }

                            }

                            @Override
                            public void onDyClick() {
                                copyToClipboard();
                                if (isAll) {
                                    ArrayList<Pair<String, String>> arrayList = new ArrayList<>();
                                    arrayList.add(new Pair<>(detail.getCoverImage(), "封面"));
                                    String[] split = detail.getImages().split(",");
                                    for (int i = 0; i < split.length; i++) {
                                        arrayList.add(new Pair<>(split[i], String.valueOf(i)));
                                    }
                                    shareImgToDyMore(arrayList);
                                } else {
                                    shareImgToDy(null, detail.getCoverImage(), String.valueOf(detail.getId()),-1);
                                }

                            }

                            @Override
                            public void onDownload() {
//                                downloadUrl(item.getImage(), item.getName());
                            }
                        }
                ).show();
    }

    private void delGallery() {
        NetworkMaster.getInstance().getCommonService().mainDel(ConfigStorage.getInstance().getToken(), String.valueOf(detail.getId()), new ServiceCallback() {
            @Override
            public void onSuccess(Object jsonObj) {
                EventBus.getDefault().post(new MessageEvent(MessageType.TYPE_ON_DETAIL_DEL));
                finish();
            }

            @Override
            public void onError(ApiException apiException) {

            }
        });
    }

    private void downloadUrl(String downLoadUrl, String fileName) {
        File folder = new File(this.getExternalCacheDir().getAbsoluteFile().getPath() + File.separator + "downloads");
        if (!folder.exists()) {
            folder.mkdirs();
        }
        File imageFile = new File(folder.getPath() + File.separator + fileName);

        if (imageFile.exists()) {
            imageFile.delete();
            try {
                imageFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        DownLoadApkUtils.download(downLoadUrl, imageFile, new DownLoadApkUtils.OnDownloadListener() {
            @Override
            public void onDownloadSuccess() {
                Log.d(TAG, "onDownloadSuccess");
                ToastUtils.showCenterToast("下载成功：" + imageFile.getAbsolutePath());
                // 其次把文件插入到系统图库
                try {
                    MediaStore.Images.Media.insertImage(getContentResolver(), imageFile.getAbsolutePath(), fileName, null);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                // 最后通知图库更新
                sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse(imageFile.getAbsolutePath())));
            }

            @Override
            public void onDownloading(float progress) {
                Log.d(TAG, "onDownloading  : " + progress);

            }

            @Override
            public void onDownloadFailed(String msg) {
                Log.d(TAG, "onDownloadFailed");
                ToastUtils.showCenterToast("下载失败：" + msg);
            }
        });
    }

    private void collect() {
        NetworkMaster.getInstance().getCommonService().mainCollectAlbum(String.valueOf(detail.getId()), new ServiceCallback() {
            @Override
            public void onSuccess(Object jsonObj) {
                detail.setCollect(1);
                collect.setCompoundDrawables(null, collectDrawable, null, null);
            }

            @Override
            public void onError(ApiException apiException) {

            }
        });
    }

    private void cancelCollect() {
        NetworkMaster.getInstance().getCommonService().mainCancelCollectAlbum(String.valueOf(detail.getId()), new ServiceCallback() {
            @Override
            public void onSuccess(Object jsonObj) {
                detail.setCollect(0);
                collect.setCompoundDrawables(null, nunCollectDrawable, null, null);

                if (FROM_TYPE_COLLECT.equals(fromType)) {
                    EventBus.getDefault().post(new MessageEvent(MessageType.TYPE_ON_DETAIL_DEL));
                    finish();
                }
            }

            @Override
            public void onError(ApiException apiException) {

            }
        });
    }

    private ViewPager2.OnPageChangeCallback changeCallback = new ViewPager2.OnPageChangeCallback() {
        @Override
        public void onPageSelected(int position) {
            Log.d(TAG, "onPageSelected: " + position);
            isShowCover = position == 0;
            changeTitle(isShowCover);
        }
    };

    private void onPhoto() {
        permissionsUtils.checkPermissions(this, permissions, new PermissionsUtils.IPermissionsResult() {
            @Override
            public void passPermissions() {
                Intent next = new Intent(DetailActivity.this, NewPhotoSynthesisActivity.class);
                next.putExtra("detail", detail);
                next.putExtra("type", 2);
                startActivity(next);
//                finish();
            }

            @Override
            public void forbidPermissions() {
                ToastUtils.showCenterToast("请打开存储权限");
            }
        });

    }


    private void copyToClipboard() {

        String desc = TextUtils.isEmpty(detail.getIntro()) ? detail.getRemark() : detail.getIntro();
        if (TextUtils.isEmpty(desc)) {
            return;
        }

        ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        if (clipboard != null) {
            ClipData clip = ClipData.newPlainText("text", desc);
            clipboard.setPrimaryClip(clip);
            ToastUtils.showCenterToast("相册简介/相册备注已复制到剪切板！");
        }
    }

    @Subscribe
    public void onMessage(MessageEvent messageEvent) {
        super.onMessage(messageEvent);
        switch (messageEvent.getType()) {
            case MessageType.TYPE_ON_SAVE_SUCCESS:
                loadData();
                break;

        }


    }

}
